package cn.usersmsg.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.usersmsg.biz.IUserBiz;
import cn.usersmsg.biz.UserBizIpml;
import cn.usersmsg.model.User;
import cn.usersmsg.util.Paging;

public class ShowUsers extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		IUserBiz iub = new UserBizIpml();
		
		String item =  req.getParameter("item");
		if ("search".equals(item)) {
			String namelike = req.getParameter("namelike");
			//获取总用户数量
			int allusers = iub.allUser(namelike).size();
			//定义每页数量
			int pagesize = 10;
			//计算总页数
			int pages = Paging.getPageCount(allusers, pagesize);
			String pageNumber = req.getParameter("pageNumber");
			int pageindex;
			if (pageNumber==null) {
				pageindex = 1;
			}else{
				pageindex = Integer.parseInt(pageNumber);
				if (pageindex>pages) {
					pageindex=1;
				}
				if (pageindex<1) {
					pageindex=pages;
				}
			}
			List<User> list = iub.getUsers(pageindex, pagesize, namelike);
			req.setAttribute("list", list);
			req.setAttribute("pages", pages);
			req.setAttribute("pageindex", pageindex);
			req.setAttribute("state", "search");
			req.setAttribute("namelike", namelike);
			req.getRequestDispatcher("usersmanage.jsp").forward(req, resp);
		}else{
		
		//获取总用户数量
		int allusers = iub.allUser().size();
		//定义每页数量
		int pagesize = 10;
		//计算总页数
		int pages = Paging.getPageCount(allusers, pagesize);
		//获取当前页码
		String pageNumber = req.getParameter("pageNumber");
		int pageindex;
		if (pageNumber==null) {
			pageindex = 1;
		}else{
			pageindex = Integer.parseInt(pageNumber);
			if (pageindex>pages) {
				pageindex=1;
			}
			if (pageindex<1) {
				pageindex=pages;
			}
		}
		List<User> list = iub.getUsers(pageindex, pagesize);
		String namelike = "";
		req.setAttribute("list", list);
		req.setAttribute("pages", pages);
		req.setAttribute("pageindex", pageindex);
		req.setAttribute("state", "all");
		req.setAttribute("namelike", namelike);
		req.getRequestDispatcher("usersmanage.jsp").forward(req, resp);
		}
	}
}
